package org.example.boot.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.example.boot.usercenter.common.BaseResponse;
import org.example.boot.usercenter.common.ResultUtils;
import org.example.boot.usercenter.common.ErrorCode;
import org.example.boot.usercenter.exception.BusinessException;
import org.example.boot.usercenter.model.User;
import org.example.boot.usercenter.model.request.UserLoginRequest;
import org.example.boot.usercenter.model.request.UserRegisterRequest;
import org.example.boot.usercenter.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static org.example.boot.usercenter.contant.UserContant.*;

/**
 * @InterfaceName: UserController
 * @Description:
 * @Author: YourName
 * @Date: 2025/1/8
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {//@RequestBody 框架识别数据进行json格式化
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"前端传来的注册信息为空");
        }
        //controller层进行数据请求本身的校验
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,planetCode)) {
           throw new BusinessException(ErrorCode.NULL_ERROR,"前端传来的注册信息(账号，密码，校验码，角色)为空");
        }
        Long result = userService.userRegiser(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {//@RequestBody 框架识别数据进行json格式化
        if (userLoginRequest == null) {
            return null;
        }
        //controller层进行数据请求本身的校验
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return null;
        }
        User result = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(result);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {//@RequestBody 框架识别数据进行json格式化
        if (request == null) {
            return null;
        }
        int result = userService.uerLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrent(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null){
            return null;
        }
        Long userId = currentUser.getId();
        // todo 校验是否合法
        User user = userService.getById(userId);
        User result = userService.getSafetyUser(user);
        return ResultUtils.success(result);
    }
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username,HttpServletRequest request){
        if (!isAdmin(request)){
            return new BaseResponse<List<User>>();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> result = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(result);
    }
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request){
        if (!isAdmin(request)){
            return new BaseResponse<>();
        }
        if (id <= 0){
            return new BaseResponse<>();
        }
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 判断是否为管理员
     * @param request 获取的角色验证id
     * @return
     */

    private boolean isAdmin(HttpServletRequest request){
        if (!isAdmin(request)){
            return false;
        }
        //仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }


}
